describe('API集成测试 - 基于实际后端响应格式', () => {
  let testData, responseCodes

  before(() => {
    cy.fixture('test-data').then((data) => {
      testData = data
      responseCodes = data.responseCodes
    })
  })

  describe('📡 后端服务连接测试', () => {
    it('应该能够连接到后端服务', () => {
      cy.apiRequest('GET', '/actuator/health')
        .then((response) => {
          expect(response.status).to.equal(200)
          expect(response.body.status).to.equal('UP')
          cy.log('✅ 后端服务健康检查通过')
        })
    })

    it('应该能够访问API文档', () => {
      cy.request({
        url: `${Cypress.env('BACKEND_URL')}/swagger-ui/index.html`,
        failOnStatusCode: false
      }).then((response) => {
        expect([200, 302]).to.include(response.status)
        cy.log('✅ Swagger文档可访问')
      })
    })
  })

  describe('📋 SMT Controller API测试', () => {
    it('应该正确处理订单查询 - 成功场景', () => {
      cy.apiRequest('GET', `/api/smt/order/${testData.orders.valid.orderNo}`)
        .then((response) => {
          expect(response.status).to.equal(200)
          expect(response.body).to.have.property('code')
          expect(response.body).to.have.property('message')
          
          if (response.body.code === responseCodes.success) {
            expect(response.body.data).to.have.property('orderNo')
            cy.log('✅ 订单查询成功')
          } else {
            cy.log(`📋 订单查询业务错误: ${response.body.code} - ${response.body.message}`)
          }
        })
    })

    it('应该正确处理订单查询 - 失败场景', () => {
      cy.apiRequest('GET', `/api/smt/order/${testData.orders.invalid.orderNo}`)
        .then((response) => {
          expect(response.status).to.equal(200) // HTTP状态码仍为200
          expect(response.body.code).to.not.equal(responseCodes.success)
          expect([
            responseCodes.orderNotFound,
            responseCodes.dataNotFound
          ]).to.include(response.body.code)
          cy.log(`✅ 正确处理无效订单: ${response.body.code}`)
        })
    })

    it('应该正确处理BOM查询', () => {
      const { orderNo, machineId, surface } = testData.orders.valid
      cy.apiRequest('GET', `/api/smt/bom/${orderNo}/${machineId}/${surface}`)
        .then((response) => {
          expect(response.status).to.equal(200)
          expect(response.body).to.have.property('code')
          
          if (response.body.code === responseCodes.success) {
            expect(response.body.data).to.be.an('array')
            cy.log('✅ BOM查询成功')
          } else {
            expect([
              responseCodes.bomNotFound,
              responseCodes.dataNotFound
            ]).to.include(response.body.code)
            cy.log(`📦 BOM查询业务结果: ${response.body.code}`)
          }
        })
    })

    it('应该正确处理扫描记录提交', () => {
      const scanRecord = {
        orderNo: testData.orders.valid.orderNo,
        mounterId: testData.orders.valid.machineId,
        smtSide: 'TOP',
        partId: testData.parts.valid[0].partId,
        rollNo: testData.parts.valid[0].rollNo,
        lotNo: testData.parts.valid[0].lotNo,
        operatorId: testData.operators.valid.operatorId,
        scanTime: new Date().toISOString()
      }

      cy.apiRequest('POST', '/api/smt/scan-record', scanRecord)
        .then((response) => {
          expect(response.status).to.equal(200)
          expect(response.body).to.have.property('code')
          expect(response.body).to.have.property('message')
          
          // 记录实际的业务响应码
          cy.log(`📝 扫描记录提交结果: ${response.body.code} - ${response.body.message}`)
          
          // 验证响应格式正确
          expect(response.body.code).to.be.a('string')
          expect(response.body.message).to.be.a('string')
        })
    })
  })

  describe('👨‍🔧 Worker Controller API测试', () => {
    it('应该正确处理作业员查询 - 成功场景', () => {
      cy.apiRequest('GET', `/api/workers/${testData.operators.valid.operatorId}`)
        .then((response) => {
          expect(response.status).to.equal(200)
          expect(response.body).to.have.property('code')
          
          if (response.body.code === responseCodes.success) {
            expect(response.body.data).to.have.property('operatorId')
            expect(response.body.data.operatorName).to.equal(testData.operators.valid.operatorName)
            cy.log('✅ 作业员查询成功')
          } else {
            cy.log(`👨‍🔧 作业员查询业务结果: ${response.body.code}`)
          }
        })
    })

    it('应该正确处理作业员查询 - 失败场景', () => {
      cy.apiRequest('GET', `/api/workers/${testData.operators.invalid.operatorId}`)
        .then((response) => {
          expect(response.status).to.equal(200) // HTTP状态码仍为200
          expect(response.body.code).to.not.equal(responseCodes.success)
          expect([
            responseCodes.userNotFound,
            responseCodes.dataNotFound
          ]).to.include(response.body.code)
          cy.log(`✅ 正确处理无效作业员: ${response.body.code}`)
        })
    })
  })

  describe('📦 Roll Controller API测试', () => {
    it('应该正确处理Roll信息查询', () => {
      const { orderNo, machineId, surface } = testData.orders.valid
      cy.apiRequest('GET', `/api/rolls/${orderNo}/${machineId}/${surface}`)
        .then((response) => {
          expect(response.status).to.equal(200)
          expect(response.body).to.have.property('code')
          
          cy.log(`📦 Roll查询结果: ${response.body.code} - ${response.body.message}`)
          
          if (response.body.code === responseCodes.success && response.body.data) {
            expect(response.body.data).to.be.an('array')
            cy.log('✅ Roll查询成功')
          }
        })
    })

    it('应该正确处理Roll验证', () => {
      const rollVerification = {
        orderNo: testData.orders.valid.orderNo,
        mounterId: testData.orders.valid.machineId,
        partId: testData.parts.valid[0].partId,
        rollNo: testData.parts.valid[0].rollNo
      }

      cy.apiRequest('POST', '/api/rolls/verify', rollVerification)
        .then((response) => {
          expect(response.status).to.equal(200)
          expect(response.body).to.have.property('code')
          cy.log(`🔍 Roll验证结果: ${response.body.code} - ${response.body.message}`)
        })
    })
  })

  describe('🔄 业务流程完整性测试', () => {
    it('应该支持完整的SMT工作流程', () => {
      // 1. 查询订单
      cy.log('📋 查询订单信息')
      cy.apiRequest('GET', `/api/smt/order/${testData.orders.valid.orderNo}`)
        .then((orderResponse) => {
          cy.log(`订单查询: ${orderResponse.body.code}`)

          // 2. 验证作业员
          cy.log('👨‍🔧 验证作业员')
          cy.apiRequest('GET', `/api/workers/${testData.operators.valid.operatorId}`)
            .then((workerResponse) => {
              cy.log(`作业员验证: ${workerResponse.body.code}`)

              // 3. 查询BOM
              cy.log('📦 查询BOM信息')
              const { orderNo, machineId, surface } = testData.orders.valid
              cy.apiRequest('GET', `/api/smt/bom/${orderNo}/${machineId}/${surface}`)
                .then((bomResponse) => {
                  cy.log(`BOM查询: ${bomResponse.body.code}`)

                  // 4. 提交扫描记录
                  cy.log('📝 提交扫描记录')
                  const scanRecord = {
                    orderNo: testData.orders.valid.orderNo,
                    mounterId: testData.orders.valid.machineId,
                    smtSide: 'TOP',
                    partId: testData.parts.valid[0].partId,
                    rollNo: testData.parts.valid[0].rollNo,
                    lotNo: testData.parts.valid[0].lotNo,
                    operatorId: testData.operators.valid.operatorId,
                    scanTime: new Date().toISOString()
                  }

                  cy.apiRequest('POST', '/api/smt/scan-record', scanRecord)
                    .then((scanResponse) => {
                      cy.log(`扫描记录提交: ${scanResponse.body.code}`)
                      
                      // 验证整个工作流程的响应都符合预期格式
                      expect(scanResponse.status).to.equal(200)
                      expect(scanResponse.body).to.have.property('code')
                      expect(scanResponse.body).to.have.property('message')
                      
                      cy.log('🎉 完整业务流程测试完成')
                    })
                })
            })
        })
    })
  })

  describe('📈 数据统计和查询测试', () => {
    it('应该支持扫描记录查询', () => {
      // 查询指定订单的扫描记录
      cy.apiRequest('GET', `/api/smt/scan-records/${testData.orders.valid.orderNo}`)
        .then((response) => {
          expect(response.status).to.equal(200)
          expect(response.body).to.have.property('code')
          
          if (response.body.code === responseCodes.success) {
            expect(response.body.data).to.be.an('array')
            cy.log('✅ 扫描记录查询成功')
          } else {
            cy.log(`📊 扫描记录查询结果: ${response.body.code}`)
          }
        })
    })

    it('应该支持按日期范围查询记录', () => {
      const today = new Date().toISOString().split('T')[0]
      const queryParams = {
        startDate: today,
        endDate: today,
        orderNo: testData.orders.valid.orderNo
      }

      const queryString = new URLSearchParams(queryParams).toString()
      cy.apiRequest('GET', `/api/smt/scan-records?${queryString}`)
        .then((response) => {
          expect(response.status).to.equal(200)
          expect(response.body).to.have.property('code')
          cy.log(`📅 日期范围查询结果: ${response.body.code}`)
        })
    })
  })
})